package cn.wedding.dao;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class BaseDao {
    public Connection connection=null;
    public PreparedStatement ps=null;
    public ResultSet rs=null;
    private String url="jdbc:mysql://localhost:3306/wedding";
    private String urname="root";
    private String password="root";
    private String driver="com.mysql.jdbc.Driver";
   /* public Connection getConnection1(){
        Connection connection=null;
        try {
            Context ctx=new InitialContext();
            DataSource ds= (DataSource) ctx.lookup("java:/comp/env/yy");
            connection=ds.getConnection();
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }*/
    public Connection getConnection(){
        Connection connection=null;
        try {
            Class.forName(driver);
            connection=DriverManager.getConnection(url,urname,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    //释放资源：
    public void closeAll(ResultSet rs,PreparedStatement ps,Connection connection){
        try {
            if(null!=rs)
                rs.close();
            if(null!=ps)
                ps.close();
            if(null!=connection&&!connection.isClosed())
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //通用增删改：
    public int exeUpdate(String sql,Object...params){
        int rows=0;
        this.connection=this.getConnection();
        try {
            ps=connection.prepareStatement(sql);
            if(null!=params){
                for(int i=0;i<params.length;i++){
                    ps.setObject((1+i),params[i]);
                }
            }
            rows=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeAll(rs,ps,connection);
        }
        return rows;
    }
    //通用查询：
    public ResultSet query(String sql,Object...params){
        connection=getConnection();
        ResultSet resultSet=null;
        try {
            ps=connection.prepareStatement(sql);
            if(null!=params){
                for(int i=0;i<params.length;i++){
                    ps.setObject((1+i),params[i]);
                }
            }
            resultSet=ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }
}

